package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"pet-track/cache"
	"pet-track/models"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	name := c.PostForm("name")
	img := c.PostForm("img")
	shu := c.PostForm("shu")

	if name == "" || img == "" || shu == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}

	data := models.Pet{
		Name: name,
		Img:  img,
		Shu:  shu,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))

	offset := (page - 1) * size

	var count int64
	models.DB.Model(&models.Pet{}).Count(&count)

	var pet []models.Pet

	redis_key := "list_pet" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Order("id desc").Offset(offset).Limit(size).Find(&pet)
		jsonData, _ := json.Marshal(pet)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &pet)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": gin.H{
			"count": count,
			"pet":   pet,
		},
	})
	return
}
func Del(c *gin.Context) {
	id := c.Query("id")

	err := models.DB.Delete(&models.Pet{}, id).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "下架失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "下架成功",
	})
	return
}
